package org.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 乱码处理
 */
@WebFilter(urlPatterns = "/",initParams = {@WebInitParam(name="encoding",value="UTF-8")})
public class EncodingFilter implements Filter {

    private String encoding ;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding = filterConfig.getInitParameter("encoding") ;
        this.encoding = encoding ;
        System.out.println("统一编码的初始化:" + encoding);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest ;
        HttpServletResponse response = (HttpServletResponse) servletResponse ;

        request.setCharacterEncoding(this.encoding);

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
    System.out.println("统一编码过滤器-销毁...");
    }
}
